﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        public void GetSqlInformation()
        {
            using (var sqlCommand = new SqlCommand(SqlGetInformation, SqlConnection, SqlTransaction))
            {
                sqlCommand.Parameters.AddWithValue("@ObjectName", SqlBulkCopy.DestinationTableName);

                using (IDataReader reader = sqlCommand.ExecuteReader())
                {
                    // PrimaryKeys & TableColumns
                    bool isDatabasePrimaryKeys = false;
                    if (Setting.PrimaryKeys == null)
                    {
                        Setting.PrimaryKeys = new List<string>();
                        isDatabasePrimaryKeys = true;
                    }
                    Setting.TableColumns = new List<string>();

                    while (reader.Read())
                    {
                        if (reader[1].ToString() == "1")
                        {
                            // IdentityColumn
                            object identityColumn = reader[0];

                            if (identityColumn != null)
                            {
                                Setting.IdentityColumn = identityColumn.ToString();
                            }
                        }
                        else if (reader[1].ToString() == "2")
                        {
                            // IsSqlServerAzure
                            Setting.IsSqlAzure = reader[0].ToString() == "1";
                        }
                        else if (reader[1].ToString() == "3")
                        {
                            if (isDatabasePrimaryKeys)
                            {
                                Setting.PrimaryKeys.Add(reader[0].ToString());
                            }
                        }
                        else
                        {
                            Setting.TableColumns.Add(reader[0].ToString());
                        }
                    }
                }
            }
        }
    }
}